#coding=utf-8
'''
copyright (c) 2019 shhao
'''
import freetype
import random
import os
import math
from tools import add_noise
import numpy as np
from utils import *
from PIL import Image
import cv2
from shapely.geometry import Polygon,MultiPoint
# from tools.profile import 

def rad(x):
    return x * np.pi / 180

def scaleBbox(bboxes, scale=1):
    for m in range(bboxes[0].shape[0]):
        for n in range(len(bboxes[0][m])):
            b = bboxes[0][m][n][:-1]
            # print(b)
            b = np.array(b).reshape((-1, 2))
            bboxes[0][m][n][:-1] = b * scale

    for m in range(bboxes[1].shape[0]):
            b = bboxes[1][m]
            b = np.array(b).reshape((-1, 2))
            bboxes[1][m] = b * scale    
    
    for m in range(bboxes[2].shape[0]):
        for n in range(len(bboxes[2][m])):
            for k in range(len(bboxes[2][m][n])):
                b = bboxes[2][m][n][k]
                b = np.array(b).reshape((-1, 2))
                bboxes[2][m][n][k] = b * scale
               
    return bboxes

def changeBbox(warpR, imageName, bboxes, dateSaveDir):
    for m in range(bboxes[0].shape[0]):
        for n in range(len(bboxes[0][m])):
            b = bboxes[0][m][n][:-1]
            # print(b)
            b = np.array(b).reshape((-1, 2))
            bb = np.ones((b.shape[0], 3))
            bb[:, :2] = b
            bb[:, 2] = 1
            pts = bb.dot(warpR.T)
            box = []
            for i in range(pts.shape[0]):
                p = [x for x in pts[i].tolist()/pts[i][-1]]
                box.append(p[:-1])
            bboxes[0][m][n][:-1] = box

    for m in range(bboxes[1].shape[0]):
            b = bboxes[1][m]
            b = np.array(b).reshape((-1, 2))
            bb = np.ones((b.shape[0], 3))
            bb[:, :2] = b
            bb[:, 2] = 1
            pts = bb.dot(warpR.T)
            box = []
            for i in range(pts.shape[0]):
                p = [x for x in pts[i].tolist()/pts[i][-1]]
                box.append(p[:-1])
            bboxes[1][m] = box    
    
    for m in range(bboxes[2].shape[0]):
        for n in range(len(bboxes[2][m])):
            for k in range(len(bboxes[2][m][n])):
                b = bboxes[2][m][n][k]
                b = np.array(b).reshape((-1, 2))
                bb = np.ones((b.shape[0], 3))
                bb[:, :2] = b
                bb[:, 2] = 1
                pts = bb.dot(warpR.T)
                box = []
                for i in range(pts.shape[0]):
                    p = [x for x in pts[i].tolist()/pts[i][-1]]
                    box.append(p[:-1])
                bboxes[2][m][n][k] = box
               
    return bboxes
            
def get_warpR(angle_range, w, h):
    anglex = np.random.randint(-angle_range, angle_range)
    angley = np.random.randint(-angle_range, angle_range)
    anglez = np.random.randint(-angle_range, angle_range)
    fov = np.random.randint(40, 60)
    # global anglex,angley,anglez,fov,w,h,r
    # 镜头与图像间的距离，21为半可视角，算z的距离是为了保证在此可视角度下恰好显示整幅图像
    z = np.sqrt(w ** 2 + h ** 2) / 2 / np.tan(rad(fov / 2))
    # 齐次变换矩阵
    rx = np.array([[1, 0, 0, 0],
                   [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0],
                   [0, -np.sin(rad(anglex)), np.cos(rad(anglex)), 0, ],
                   [0, 0, 0, 1]], np.float32)
 
    ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0],
                   [0, 1, 0, 0],
                   [-np.sin(rad(angley)), 0, np.cos(rad(angley)), 0, ],
                   [0, 0, 0, 1]], np.float32)
 
    rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0],
                   [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0],
                   [0, 0, 1, 0],
                   [0, 0, 0, 1]], np.float32)
 
    r = rx.dot(ry).dot(rz)
 
    # 四对点的生成
    pcenter = np.array([h / 2, w / 2, 0, 0], np.float32)
 
    p1 = np.array([0, 0, 0, 0], np.float32) - pcenter
    p2 = np.array([w, 0, 0, 0], np.float32) - pcenter
    p3 = np.array([0, h, 0, 0], np.float32) - pcenter
    p4 = np.array([w, h, 0, 0], np.float32) - pcenter
 
    dst1 = r.dot(p1)
    dst2 = r.dot(p2)
    dst3 = r.dot(p3)
    dst4 = r.dot(p4)
 
    list_dst = [dst1, dst2, dst3, dst4]
 
    org = np.array([[0, 0],
                    [w, 0],
                    [0, h],
                    [w, h]], np.float32)
 
    dst = np.zeros((4, 2), np.float32)
 
    # 投影至成像平面
    for i in range(4):
        dst[i, 0] = list_dst[i][0] * z / (z - list_dst[i][2]) + pcenter[0]
        dst[i, 1] = list_dst[i][1] * z / (z - list_dst[i][2]) + pcenter[1]
 
    warpR = cv2.getPerspectiveTransform(org, dst)
    return warpR

def AddImageNoiseRandom(img):
    choice = random.random()
    if choice <= 0.1:
        # print("add gaussian noise")
        return add_noise.add_gaussian_noise(img, 0, 0.001)
    elif choice <= 0.2:
        # print("add sp noise")
        return add_noise.add_sp_noise(img, 0.01)
    else:
        # print("not add noise")
        return img

def get_warp_boxes(warpR, boxxes):
    b = np.array(boxxes, dtype=np.float32).reshape((-1, 2))
    bb = np.ones((b.shape[0], 3))
    bb[:, :2] = b
    bb[:, 2] = 1
    pts = bb.dot(warpR.T)
    box = []
    for i in range(pts.shape[0]):
        p = [x for x in pts[i].tolist()/pts[i][-1]]
        box.append(p[:-1])
    box_array = np.array(box, dtype=np.float32)
    # print(box_array)
    # input()
    return box_array   

def boxxes_judge(warp_boxxes, w, h):
    width = w
    height = h
    picturePoint = [0,0, 0,height, width,height, width,0, 0,0]
    picturePoint = np.array(picturePoint, dtype=np.float32).reshape(5, 2)
    picturePoly = Polygon(picturePoint)
    length = int(len(warp_boxxes) / 4)
    Outarea = []
    area_value = []
    for i in range(length):
        temp = [warp_boxxes[4*i], warp_boxxes[4*i+1], warp_boxxes[4*i+2], warp_boxxes[4*i+3], warp_boxxes[4*i]]
        temp = np.array(temp, dtype=np.float32).reshape(5, 2)
        tempPoly = Polygon(temp)
        area = picturePoly.intersection(tempPoly)
        try:
            Outarea.append(list(area.exterior.coords[0:-1]))
            area_value.append(area.area)
        except Exception as e:
            print('Exception ', temp)
            Outarea.append(None)
            area_value.append(None)
            continue

    return Outarea,area_value

def BoxxesVisualization(img,  txt_area, image_area):
    temp = img

    for i in range(len(txt_area)):
        if txt_area[i] is None:
            continue
        pts = np.array([txt_area[i]], dtype = np.int32)
        cv2.polylines(temp, pts, True,(0,255,255),1)

    for i in range(len(image_area)):
        if image_area[i] is None:
            continue
        pts = np.array([image_area[i]], dtype = np.int32)
        cv2.polylines(temp, pts, True,(0,255,255),1)
        
    return temp

def changeAttr_txt(attr_txt):
    temp = attr_txt
    title_index = []
    txt_index = []
    for idx, char in enumerate(temp):
        if char == 'title':
            title_index.append(idx)
        if char == 'text':
            txt_index.append(idx)
    
    for i in range(len(txt_index)):
        index = txt_index[i]
        attr = temp[index] + '_' + str(i+1)
        temp[index] = attr
    for i in range(len(title_index)):
        index = title_index[i]
        attr = temp[index] + '_' + str(i+1)
        temp[index] = attr
    return temp

def changeAttr_img(attr_img):
    temp = attr_img
    image_index = []
    table_index = []
    formula_index = []
    for idx, char in enumerate(temp):
        if 'image' in char :
            image_index.append(idx)
        if 'table' in char:
            table_index.append(idx)
        if 'formula' in char:
            formula_index.append(idx)

    for i in range(len(image_index)):
        index = image_index[i]
        attr = 'image' + '_' + str(i+1)
        temp[index] = attr
    for i in range(len(table_index)):
        index = table_index[i]
        attr = 'table' + '_' + str(i+1)
        temp[index] = attr
    for i in range(len(formula_index)):
        index = formula_index[i]
        attr = 'formula' + '_' + str(i+1)
        temp[index] = attr

    return temp

def draw_edge_line(surface, edges, H, W):
    # x1,y1 = int(edges['l'] * W), int(edges['t'] * H)
    # x2,y2 = int(W * (1 - edges['r'])), int(H *(1 - edges['b']))
    for k,v in edges.items():
        if v == 0:
            continue
        print("-------------------------------------------------------------")
        if k == 't':
            # cv2.line(surface, (x1,y1), (x2,y1), (0,0,0))#, thickness[, lineType[, shift]]])
            rv = random.random()
            if rv < 0.3:
                cv2.line(surface, (edges['t'][0][0] + 10, edges['t'][0][1]), (edges['t'][1][0]-10, edges['t'][1][1]), (0,0,0))
            elif rv < 0.5:
                cv2.line(surface, (edges['t'][0][0] + 10, edges['t'][0][1]), (edges['t'][1][0]-10, edges['t'][1][1]), (0,0,0), 2)
        elif k == 'b':
            # cv2.line(surface, (x1,y1), (x1, y2), (0,0,0))
            rv = random.random()
            if rv < 0.3:
                cv2.line(surface, (edges['b'][0][0] + 10, edges['b'][0][1]), (edges['b'][1][0]-10, edges['b'][1][1]), (0,0,0))
            elif rv < 0.5:
                cv2.line(surface, (edges['b'][0][0] + 10, edges['b'][0][1]), (edges['b'][1][0]-10, edges['b'][1][1]), (0,0,0), 2)
        elif k == 'l':
            # cv2.line(surface, (x2,y1), (x2, y2), (0,0,0))
            rv = random.random()
            if rv < 0.5:
                cv2.line(surface, (edges['l'][0][0], edges['l'][0][1]+10), (edges['l'][1][0], edges['l'][1][1]-10), (0,0,0))
            elif rv < 0.8:
                cv2.line(surface, (edges['l'][0][0], edges['l'][0][1]+10), (edges['l'][1][0], edges['l'][1][1]-10), (0,0,0), 2)
        else:
            # cv2.line(surface, (x1,y2), (x2, y2), (0,0,0))
            rv = random.random()
            if rv < 0.5:
                cv2.line(surface, (edges['r'][0][0], edges['r'][0][1]+10), (edges['r'][1][0], edges['r'][1][1]-10), (0,0,0))
            elif rv < 0.8:
                cv2.line(surface, (edges['r'][0][0], edges['r'][0][1]+10), (edges['r'][1][0], edges['r'][1][1]-10), (0,0,0), 2)
    return surface

def main(font_size=(25, 45, 30), scale=1.0, region_image_type=0, thresh_color=(0, 80), addWarp=False, angle_range=30, dateSaveDir="./synthetic_data/", page_config=None, random_bg=False, save_layout=False):

    # code for test font
    fontSet = []
    fontPath = "./font/en"
    for _, _, filenames in os.walk(fontPath):
        for filename in filenames:
            if filename.endswith('ttf'):
                fontSet.append(filename)
        
    if page_config is not None:
        config = page_config
    else:
        import config
    print("Page config file is: {}".format(config))
    # input()
    # Create folder for saving synthetic Layout images
    if not os.path.exists(os.path.join(dateSaveDir, 'image/')):
        os.makedirs(os.path.join(dateSaveDir, 'image/'))    
    if not os.path.exists(os.path.join(dateSaveDir, 'regionInfo/')):
        os.makedirs(os.path.join(dateSaveDir, 'regionInfo/'))
    if save_layout:
        layout_image = np.full((config.picHeight, config.picWidth, 3), 0, dtype=np.ubyte)
        if not os.path.exists(os.path.join(dateSaveDir, 'procfile_image/')): 
            os.makedirs(os.path.join(dateSaveDir, 'procfile_image/'))

    image_names = []
    init_index = 0
    if os.path.exists(dateSaveDir + "image_names.npy"):
        image_names = np.load(dateSaveDir + "image_names.npy").tolist()
        init_index += (int)(image_names[-1].split('_')[0])
        print("*******Continue to generate page from index*********", init_index)

    # Page backgground
    surface = np.full((config.picHeight, config.picWidth, 3), 255,dtype=np.ubyte)
    paperbk_name = '0.jpg'
    rv = random.random()
    if random_bg:
        paperbkPath = os.path.join('./content', 'paperbackground')
        paperbkSet = []
        for _, _, filenames in os.walk(paperbkPath):
            for filename in filenames:
                if filename.endswith('jpg'):
                    paperbkSet.append(filename)
        paperbk_name = random.choice(paperbkSet)
        # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@ ", paperbk_name)
        paperbkimg = Image.open(os.path.join('./content/paperbackground', paperbk_name))
        paperbkimg = paperbkimg.resize((config.picWidth, config.picHeight))
        paperbkimg = paperbkimg.convert("RGB")
        array_img = np.array(paperbkimg)
        surface = array_img
    
    # Page marginal line of top/bottom/left/right
    surface = draw_edge_line(surface, config.edges, config.picHeight, config.picWidth)

    train_mask = np.full((config.picHeight, config.picWidth), 255, dtype=np.ubyte)
    name = init_index + 1 
    imageName = str(name) + '_' + str(config.numRegion) + '_' + paperbk_name.split('.')[0]
    print("\033[31mStart generate image: {}\033[0m".format(imageName))

    readdir = random.randint(0,1)      # 阅读顺序,中、日文有效 
    bboxes = []
    modify_region= []
    attr_txt = [] #存放文字区域的属性  shapely
    boxxes_txt = []
    attr_image = []#存放图片区域的属性
    boxxes_image = []
    jpgpath = None
    width_max = config.picWidth
    height_max = config.picHeight
    for region_i in range(config.numRegion):
        print("\033[32mCurrent region type: {}\033[0m".format(config.regionList[region_i]['attr']))
        
        # 版面布局信息可视化图像保存, 方便与生成的图像布局对照, 
        # 生成的图像布局信息可视化: 数据集生成后执行 python ./tools/profile.py
        # 两个布局可视化图像保存在同一目录下 默认为 ./synthetic_data/procfile_image/
        if save_layout:
            rx = config.regionList[region_i]['x']
            ry = config.regionList[region_i]['y']
            rh = config.regionList[region_i]['h']
            rw = config.regionList[region_i]['w']
            cv2.rectangle(layout_image, (rx, ry), (rx+rw, ry+rh), (255,255,255), 2)
            region_type = config.regionList[region_i]['attr']
            if 'image' in config.regionList[region_i]['attr']:
                region_type = 'image'
            if 'table' in config.regionList[region_i]['attr']:
                region_type = 'table'              
            # cv2.putText(layout_image, region_type, (rx+rw//2, ry+rh//2), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 0, 0), 2)
            cat_size = cv2.getTextSize(region_type, cv2.FONT_HERSHEY_SIMPLEX, 3, 2)[0]
            cv2.putText(layout_image, region_type, (rx, ry+(rh-cat_size[1])//2+cat_size[1]-2), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2, lineType=cv2.LINE_AA)

        # 图像区域填充
        # fontCls = FontClass(config, surface, imageName, dateSaveDir, region_image_type=region_image_type, font_name=os.path.join(fontPath,fontSet[i]))
        rects_heading = None
        rv = random.random()
        if rv < 0.5 and config.regionList[region_i]['attr'] == 'text' and config.regionList[region_i]['lan'] == 'en' and config.regionList[region_i]['dir'] == 'h' and config.regionList[region_i]['h'] > 120:
            # tempDict = config.regionList[region_i].copy()
            fontCls = FontClass(config, region_i, surface, imageName, dateSaveDir, region_image_type=region_image_type, font_size=font_size, thresh_color=thresh_color, isheading=True, random_bg=random_bg)
            surface, rects_heading = fontCls.render()
            heading_size = fontCls.size
            fontCls = FontClass(config, region_i, surface, imageName, dateSaveDir, region_image_type=region_image_type, font_size=(font_size[1], heading_size, font_size[2]), thresh_color=thresh_color, random_bg=random_bg)
            surface, rects = fontCls.render()
        else:
            fontCls = FontClass(config, region_i, surface, imageName, dateSaveDir, region_image_type=region_image_type, font_size=font_size, thresh_color=thresh_color, random_bg=random_bg, readir=readdir)
            surface, rects = fontCls.render()            
        if rects_heading is not None:
            if len(rects) == 0:
                rects = rects_heading
            elif len(rects_heading)>0:
                rects[0].extend(rects_heading[0])
                rects[1].extend(rects_heading[1])
                rects[2].extend(rects_heading[2])
                rects[3].extend(rects_heading[3])

        # 区域框信息处理（词rects[0]、文本行rects[1]、字符rects[2]、段落rects[3]）
        # rects[0]除了包含框坐标以外还包含词文本
        if len(bboxes) == 0 and len(rects) > 0:
            bboxes = rects[:-1]
        elif len(rects) > 0:
            bboxes[0].extend(rects[0])  
            bboxes[1].extend(rects[1])  
            bboxes[2].extend(rects[2])  
            # bboxes[3].extend(rects[3])
        if config.regionList[region_i]['attr'] != 'formula':
            if len(rects) == 0:
                continue
            for i, region_rect in enumerate(rects[3]):
                if scale != 1:
                    region_rect = np.array(region_rect) * scale
                    region_rect = region_rect.tolist()
                tempDict = {}
                tempDict['attr']= config.regionList[region_i]['attr']
                if rects_heading is not None and len(rects_heading)>0 and i == len(rects[3])-1:
                    tempDict['attr'] = 'title'
                if config.regionList[region_i]['attr'] != 'title' and config.regionList[region_i]['attr'] != 'text':
                    tempDict['attr'] = 'text'      
                tempDict['x'] = region_rect[0]
                tempDict['y'] = region_rect[1]
                tempDict['h'] = region_rect[-1] - region_rect[1]
                tempDict['w'] = region_rect[2] - region_rect[0]
                modify_region.append(tempDict)
                # attr_txt.append(config.regionList[region_i]['attr'])
                attr_txt.append(tempDict['attr'])
                # temp = [x_min, y_min, x_min, y_max, x_max, y_max, x_max, y_min]#x0,y0
                boxxes_txt.append([region_rect[0], region_rect[1], region_rect[6], region_rect[7], region_rect[4], region_rect[5], region_rect[2], region_rect[3]])
        if config.regionList[region_i]['attr'] != 'title' and config.regionList[region_i]['attr'] != 'text':
            if len(rects) == 0 and config.regionList[region_i]['attr'] == 'table': # 表格没有绘制成功，无需添加区域信息
                continue

            if scale != 1:
                train_mask = cv2.resize(train_mask, (int(config.picWidth*scale), int(config.picHeight*scale)))

            mask_x = config.regionList[region_i]['x'] = config.regionList[region_i]['x'] * scale
            mask_y = config.regionList[region_i]['y'] = config.regionList[region_i]['y'] * scale
            mask_h = config.regionList[region_i]['h'] = config.regionList[region_i]['h'] * scale
            mask_w = config.regionList[region_i]['w'] = config.regionList[region_i]['w'] * scale

            modify_region.append(config.regionList[region_i])
            
            cv2.drawContours(train_mask, [np.array([[mask_x,mask_y],[mask_x+mask_w,mask_y],[mask_x+mask_w,mask_y+mask_h],[mask_x,mask_y+mask_h]]).astype(np.int32)], 0,
                        0, -1)
            attr_image.append(config.regionList[region_i]['attr'])
            x0 = config.regionList[region_i]['x']
            y0 = config.regionList[region_i]['y']
            x1 = config.regionList[region_i]['x'] + config.regionList[region_i]['w']
            y1 = config.regionList[region_i]['y'] + config.regionList[region_i]['h']
            temp = [x0, y0, x0, y1, x1, y1, x1, y0]
            boxxes_image.append(temp)

    if save_layout:
        cv2.imwrite(dateSaveDir + 'procfile_image/' + imageName + '_layout.jpg', layout_image)

    # print(attr_image,attr_txt)
    # print(boxxes_txt)
    # print(boxxes_image)

    # im.save(dateSaveDir + 'image/' + imageName + fontSet[i].split('.')[0] + '.jpg') #for test font
    # im.save(dateSaveDir + 'image/' + imageName + '.jpg')
    # image_names.append(imageName + '.jpg')

    # 保存所有文本框，索引0,1,2分别是
    # 词: x0, y0, x1, y1, x2, y2, x3, y3, word_str
    # 文本行: x0, y0, x1, y1, x2, y2, x3, y3
    # 字符框: x0, y0, x1, y1, x2, y2, x3, y3

    surface = AddImageNoiseRandom(surface)
    bboxes = np.array(bboxes)

    print("\033[32mImage and Data processing and save!!!\033[0m")
    if scale != 1:
        bboxes = scaleBbox(bboxes, scale)
        surface = cv2.resize(surface, (int(config.picWidth*scale), int(config.picHeight*scale)))
    
    if addWarp:
        h, w = surface.shape[0:2]
        warpR = get_warpR(angle_range, w, h)
        surface = cv2.warpPerspective(surface, warpR, (w, h))#, borderMode=cv2.BORDER_REPLICATE)
        # train_mask = cv2.warpPerspective(train_mask, warpR, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=255)
        # cv2.imwrite(dateSaveDir + 'image/mask_' + imageName + '_warp.jpg', train_mask)

        if not os.path.exists(dateSaveDir + 'regionInfo/' + imageName + '_warp'):
            os.makedirs(dateSaveDir + 'regionInfo/' + imageName + '_warp')
        warp_bboxes = changeBbox(warpR, imageName, bboxes, dateSaveDir)

        warp_txt = get_warp_boxes(warpR, boxxes_txt)
        warp_image = get_warp_boxes(warpR, boxxes_image)
        area_txt , area_txt_value = boxxes_judge(warp_txt, width_max, height_max)
        area_image, area_image_value  = boxxes_judge(warp_image, width_max, height_max)   
        np.save(dateSaveDir + 'regionInfo/' + imageName + "_warp/bboxes.npy", warp_bboxes)            
        im = Image.fromarray(surface)
        jpgpath = dateSaveDir + 'image/' + imageName + '_warp.jpg'
        im.save(jpgpath)
        image_names.append(imageName + '_warp.jpg')
    else:
        # cv2.imwrite(dateSaveDir + 'image/mask_' + imageName + '.jpg', train_mask)
        if not os.path.exists(dateSaveDir + 'regionInfo/' + imageName):
            os.makedirs(dateSaveDir + 'regionInfo/' + imageName)
        np.save(dateSaveDir + 'regionInfo/' + imageName + "/bboxes.npy", bboxes)
        im = Image.fromarray(surface)
        jpgpath = dateSaveDir + 'image/' + imageName + '.jpg'
        im.save(jpgpath)
        image_names.append(imageName + '.jpg')
        area_txt, area_image = boxxes_txt, boxxes_image

    if addWarp:
        surface = BoxxesVisualization(surface, area_txt, area_image) #可视化部分
    else:
        surface = BoxxesVisualization(surface, np.array(area_txt, dtype=np.float32).reshape(-1, 4, 2), np.array(area_image, dtype=np.float32).reshape(-1, 4, 2)) #可视化部分
        
    # cv2.namedWindow('image', 0)
    # cv2.imwrite('area_txt.jpg',surface)
    # cv2.waitKey(0)

    attr_txt = changeAttr_txt(attr_txt)
    attr_image = changeAttr_img(attr_image)
    #写入warp之后的框和其对应属性
    warp_regionList = []
    for i in range(len(area_txt)):
        if area_txt[i] is None:
            continue
        temp = {}
        temp['attr'] = attr_txt[i]
        temp['segmentation'] = list(np.array(area_txt[i], dtype=np.float32).flatten())
        if addWarp:
            temp['area'] = area_txt_value[i] 
        else:
            temp['area'] = (boxxes_txt[i][5] - boxxes_txt[i][1]) * (boxxes_txt[i][4] - boxxes_txt[i][0])
        warp_regionList.append(temp)

    for i in range(len(area_image)):
        if area_image[i] is None:
            continue
        temp = {}
        temp['attr'] = attr_image[i]
        temp['segmentation'] = list(np.array(area_image[i], dtype=np.float32).flatten())
        if addWarp:
            temp['area'] = area_image_value[i]
        else:
            temp['area'] = (area_image[i][5] - area_image[i][1]) * (area_image[i][4] - area_image[i][0])
        warp_regionList.append(temp)

    #将图像名写入config，以便生成xml
    # jpgpath = dateSaveDir + 'image/'+imageName+'.jpg'
    # warpPath = dateSaveDir + 'image/'+imageName+'_warp.jpg'
    tempDict = {}
    tempDict['jpgPath']= jpgpath
    # tempDict['warp_jpgPath'] = warpPath
    target = './config.py'
    f = open(target, 'a')
    f.write('normal_imageName = {}\n'.format(tempDict))       # image path
    f.write('modify_region = {}\n'.format(modify_region))     # for voc(xml) 
    f.write('warp_regionList = {}\n'.format(warp_regionList)) # for coco(json)
    f.close()

    #保存图像名称，以便索引
    with open(os.path.join(dateSaveDir, 'train.txt'), 'w') as f:
        for imageName in image_names:
            f.write(imageName)
            f.write('\n')
    image_names = np.array(image_names)
    np.save(dateSaveDir + 'image_names.npy', image_names)

    print("\033[31mEnd generate image: {}\033[0m".format(imageName))

    if page_config is not None:
        config.set_gts(tempDict, modify_region, warp_regionList)
        return config

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="!!!!!!!!!!!!Main process of LayoutGen!!!!!!!!!!!!!")
    parser.add_argument(
        '-sd',
        "--dateSaveDir", 
        default="./synthetic_data/", 
        type=str, 
        help="Layout data folder(last slash required)")
    parser.add_argument(
        '-it',
        "--region_image_type", 
        default=0, 
        type=int, 
        help="Type of image to be inserted")
    parser.add_argument(
        "-fs",
        "--font_size", 
        default=(25, 45, 30), 
        type=tuple, 
        help="Define font size of text")
    parser.add_argument(
        "-tc",
        "--thresh_color", 
        default=(0, 80), 
        type=tuple, 
        help="Define color diff val between bg and fg")
    parser.add_argument(
        '-s',
        "--scale", 
        default=1.0, 
        type=float, 
        help="image scale factor")
    parser.add_argument(
        '-aw',
        "--addWarp", 
        default=False, 
        action='store_true', 
        help="Gen warp image data")
    parser.add_argument(
        '-ar',
        "--angle_range", 
        default=30, 
        type=int, 
        help="Range of Warp angle")
    opt = parser.parse_args()

    main(opt.font_size, opt.scale, opt.region_image_type, opt.thresh_color, opt.addWarp, opt.angle_range, opt.dateSaveDir, page_config=None)